package com.kehao.leetcode.jzoffer;

import org.junit.Test;

public class JZSolution054 {

    private static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }


    int sum = 0;
    public TreeNode convertBST(TreeNode root) {
        sum=0;
        if(root==null) return null;
        dfs1(root);
        dfs2(root,sum);
        return root;
    }

    private void dfs2(TreeNode root, int sum) {
        if(root == null) return;
        root.val = sum- root.val;
        dfs2(root.left,sum);
        dfs2(root.right,sum);
    }

    // return the sum of subTree
    private int dfs1(TreeNode root) {
        if(root==null) return 0;
        int val = root.val;
        int leftSum = dfs1(root.left);
        root.val = sum;
        sum+=val;
        int rightSum = dfs1(root.right);
        return leftSum+rightSum+val;
    }

    @Test
    public void test01(){
        TreeNode root = buildTree(new Integer[]{4, 1, 6, 0, 2, 5, 7, null, null, null, 3, null, null, null, 8});
        TreeNode newRoot = convertBST(root);
    }


    private TreeNode buildTree(Integer[] treeArray){
        TreeNode[] treeNodeList = new TreeNode[treeArray.length];
        for (int i = 0; i < treeArray.length; i++) {
            if(treeArray[i]!=null){
                treeNodeList[i] = new TreeNode(treeArray[i]);
            }
        }
        for (int i = 0; i < treeNodeList.length/2; i++) {
            if(i*2+1<treeNodeList.length){
                treeNodeList[i].left = treeNodeList[i*2+1];
            }
            if(i*2+2<treeNodeList.length){
                treeNodeList[i].right = treeNodeList[i*2+2];
            }
        }
        return treeNodeList[0];
    }
}
